package org.xfy.pet.controller;

import org.xfy.base.util.JwtUtils;
import org.xfy.base.util.Payload;
import org.xfy.org.domain.LoginData;
import org.xfy.pet.service.IPetService;
import org.xfy.pet.domain.Pet;
import org.xfy.pet.query.PetQuery;
import org.xfy.base.util.AjaxResult;
import org.xfy.base.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 后端接口类；
 */
@RestController
@RequestMapping("/pet")
public class PetController {

    @Autowired
    public IPetService petService;

    /**
     * 上架
     * @param ids
     * @return
     */
    @PostMapping("/onsale")
    public AjaxResult onsale(@RequestBody Long[] ids){
        return petService.onsale(ids);
    }

    /**
     * 下架
     * @param ids
     * @return
     */
    @PostMapping("/offsale")
    public AjaxResult offsale(@RequestBody Long[] ids){
        return petService.offsale(ids);
    }

    /**
     * 接口：添加或修改
     *
     * @param pet 传递的实体
     * @return AjaxResult 响应给前端
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Pet pet, HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        Payload<LoginData> payload = JwtUtils.getdecode(token);
        LoginData loginData = payload.getLoginData();
        if (pet.getId() != null) {
            petService.update(pet);
        } else {
            petService.add(pet,loginData);
        }
        return AjaxResult.me();

    }

    /**
     * 接口：删除
     *
     * @param id
     * @return AjaxResult 响应给前端
     */
    @DeleteMapping(value = "/{id}")
    public AjaxResult del(@PathVariable("id") Long id) {
        petService.del(id);
        return AjaxResult.me();
    }

    /**
     * 接口：批量删除
     *
     * @param ids
     * @return AjaxResult 响应给前端
     */
    @PatchMapping
    public AjaxResult patchDel(@RequestBody Long[] ids) {
        petService.patchDel(ids);
        return AjaxResult.me();
    }

    /**
     * 接口：查询单个对象
     *
     * @param id
     */
    @GetMapping("/{id}")
    public Pet findOne(@PathVariable("id") Long id) {
        return petService.findOne(id);
    }


    /**
     * 接口：查询所有
     *
     * @return
     */
    @GetMapping
    public List<Pet> findAll() {
        return petService.findAll();
    }


    /**
     * 接口：分页查询或高级查询
     *
     * @param query 查询对象
     * @return PageList 分页对象
     */
    @PostMapping("/pageList")
    public PageList<Pet> queryPage(@RequestBody PetQuery query,HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        Payload<LoginData> payload = JwtUtils.getdecode(token);
        LoginData loginData = payload.getLoginData();
        return petService.queryPage(query,loginData);
    }
}
